<script setup lang="ts">
import {useRoute} from "vue-router";
import {
  create,
  exportExcel,
  deleteById,
  batchDelete,
  update,
  listPage,
  getById,
} from "@/apis/careful-ui/tools/dict";

import {useScreenStore} from "@/hooks/screen";
import {skyNoticeSuccess, skyNoticeError, skyMsgError, skyMsgWarning, skyMsgBox, skyMsgInfo, skyMsgSuccess} from "@/utils/sky.js";

const route = useRoute();
const {isScreen} = useScreenStore();

const skyExcelRef = ref();
const skyDrawerRef = ref();
const formRef = ref();

const pageData = reactive({
  showSearch: true,
  pageParams: {
    page: 1,
    pageSize: 10,
    creator: null,
    modifier: null,
    status: true,
    name: "",
    code: "",
    type: null,
    valueType: null,
  },
  ids: [],
  single: true,
  multiple: true,
  title: "",
  confirmLoading: false,
  form: {
    id: null,
    name: "",
    code: "",
    type: 1,
    valueType: 1,
    sort: 1,
    belong_dept: null,
    remark: null,
  },
  rules: {
    name: [{required: true, message: "请输入字典名称", trigger: "blur"}],
    code: [{required: true, message: "请输入字典编号", trigger: "blur"}],
  },
  loading: false,
  total: 0,
  showTable: [
    {title: "字典名称", visible: 1},
    {title: "字典编码", visible: 1},
    {title: "字典类型", visible: 1},
  ],
  tableList: [],
});
const method = reactive({
  /** 搜索 */
  handleSearch: () => {
    pageData.pageParams.page = 1;
    pageData.pageParams.pageSize = 10;
    method.handleListPage();
  },
  /** 重置 */
  resetSearch: () => {
    method.resetSearchParams();
    method.handleListPage();
  },
  /** 重置搜索参数 */
  resetSearchParams: () => {
    pageData.pageParams = {
      page: 1,
      pageSize: 10,
      creator: null,
      modifier: null,
      status: true,
      name: "",
      code: "",
      type: null,
      valueType: null,
    };
  },
  /** 添加 */
  handleAdd: () => {
    // 打开弹出框
    skyDrawerRef.value.skyOpen();
    // 重置表单
    method.resetForm();
    // 标题
    pageData.title = "添加";
  },
  /** 删除 */
  handleDelete: (row: any) => {
    const id = row.id;
    if (id === null || id === "") {
      skyMsgWarning("请选中需要删除的数据🌻");
      return;
    }
    skyMsgBox("您确认需要删除名称[" + row.name + "]么？")
      .then(async () => {
        try {
          await deleteById(id);
          skyNoticeSuccess("删除成功🌻");
        } catch (error) {
          skyNoticeError(`删除失败，请刷新重试🌻【${error}】`);
        } finally {
          await method.handleListPage();
        }
      })
      .catch(() => {
        skyMsgError("已取消🌻");
      });
  },
  /** 批量删除 */
  handleBatchDelete: () => {
    if (pageData.value.ids.length == 0) {
      skyMsgInfo("请选择需要删除的数据🌻");
      return;
    }
    skyMsgBox("您确认需要进行批量删除么？")
      .then(async () => {
        try {
          // const res: any = await batchDelete(pageData.value.ids);
          skyNoticeSuccess(`${res.msg}`);
        } catch (error) {
          skyNoticeSuccess("批量删除失败，请刷新重试🌻");
        } finally {
          await method.handleListPage();
        }
      })
      .catch(() => {
        skyMsgError("已取消🌻");
      });
  },
  /** 修改 */
  handleUpdate: (row: any) => {
    // 打开弹出框
    skyDrawerRef.value.skyOpen();
    // 重置表单
    method.resetForm();
    pageData.title = "修改";
    const id = row ? row.id : pageData.ids[0];
    if (id == null || id === "") {
      skyMsgError("请选中需要修改的数据🌻");
    }
    // 回显数据
    method.handleEcho(id);
  },
  /** 回显数据 */
  handleEcho: async (id: any) => {
    if (id === null || id === "") {
      skyMsgWarning("请选择需要修改的数据🌻");
      return;
    }
    try {
      const res = await getById(id);
      pageData.form = res.data;
    } catch (error) {
      skyNoticeError("数据获取失败，请刷新重试🌻");
    }
  },
  /** 确定  */
  handleConfirm: () => {
    if (!formRef.value) return;
    pageData.confirmLoading = true;
    (formRef.value).validate(async (valid: any) => {
      if (valid) {
        if (pageData.form.id) {
          try {
            await update(pageData.form);
            skyNoticeSuccess("修改成功🌻");
          } catch (error) {
            skyNoticeError(`修改失败，请刷新重试🌻【${error}】`);
          }
        } else {
          try {
            await create(pageData.form);
            skyNoticeSuccess("添加成功🌻");
          } catch (error) {
            skyNoticeError(`添加失败，请刷新重试🌻【${error}】`);
          }
        }
        pageData.confirmLoading = false;
        skyDrawerRef.value.skyQuickClose();
        await method.resetForm();
        await method.handleListPage();
      } else {
        skyMsgError("验证失败，请检查填写内容🌻");
        pageData.confirmLoading = false;
      }
    });
  },
  /** 取消 */
  handleCancel: () => {
    skyDrawerRef.value.skyClose();
  },
  /** 清空表单数据 */
  resetForm: () => {
    nextTick(() => {
      if (formRef.value) {
        // 重置该表单项，将其值重置为初始值，并移除校验结果
        formRef.value.resetFields();
      }
    });
    pageData.form = {
      id: null,
      name: "",
      code: "",
      type: 1,
      valueType: 1,
      sort: 1,
      belong_dept: null,
      remark: null,
    };
  },

  /** 是否多选 */
  handleSelectionChange: (selection: any) => {
    pageData.ids = selection.map((item: any) => item.id);
    pageData.single = selection.length !== 1; // 单选
    pageData.multiple = !selection.length; // 多选
  },
  /** 数据表格 */
  handleListPage: async () => {
    try {
      pageData.loading = true;
      pageData.tableList = [];
      const res: any = await listPage(pageData.pageParams);
      pageData.total = res.data.total;
      pageData.tableList = res.data.list;
    } catch (error) {
      skyMsgError(`数据查询失败，请刷新重试🌻【${error}】`);
    } finally {
      pageData.loading = false;
    }
  },
});
onMounted(() => {
  method.handleListPage();
});
</script>

<template>
  <div class="sky-flex">
    <SkyCard>
      <!-- 搜索条件 -->
      <el-form v-show="pageData.showSearch" :inline="true" label-width="80px">
        <el-form-item label="字典名称" prop="name">
          <el-input
            style="width: 160px"
            placeholder="字典名称"
            v-model="pageData.pageParams.name"
            clearable
            @keyup.enter.native="method.handleSearch"
          ></el-input>
        </el-form-item>
        <el-form-item label="字典编码" prop="code">
          <el-input
            style="width: 160px"
            placeholder="字典编码"
            v-model="pageData.pageParams.code"
            clearable
            @keyup.enter.native="method.handleSearch"
          ></el-input>
        </el-form-item>
        <el-form-item label="状态" prop="status">
          <el-select v-model="pageData.pageParams.status" style="width: 160px" clearable>
            <el-option label="启用" :value="true"/>
            <el-option label="禁用" :value="false"/>
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" icon="search" plain v-throttle="method.handleSearch">搜索</el-button>
          <el-button type="danger" icon="refresh" plain v-debounce="method.resetSearch">重置</el-button>
        </el-form-item>
      </el-form>
      <!-- 表格头部按钮 -->
      <el-row :gutter="10">
        <el-col :span="1.5">
          <el-button type="primary" icon="plus" plain @click="method.handleAdd()">新增</el-button>
        </el-col>
        <el-col :span="1.5">
          <el-button type="danger" icon="delete" plain @click="method.handleBatchDelete()" :disabled="pageData.multiple">
            删除
          </el-button>
        </el-col>
        <el-col :span="1.5">
          <el-button type="success" icon="edit" plain @click="method.handleUpdate(null)" :disabled="pageData.single">
            修改
          </el-button>
        </el-col>
      </el-row>
      <br/>
      <!-- 表格头部按钮 -->

      <!-- 数据表格 -->
      <el-table
        v-loading="pageData.loading"
        border
        stripe
        :data="pageData.tableList"
        empty-text="暂时没有数据哟🌻"
        @selection-change="method.handleSelectionChange"
      >
        <el-table-column type="selection" width="55" align="center" fixed="left"/>
        <el-table-column label="字典名称" prop="name" width="150" align="center" sortable :show-overflow-tooltip="true"/>
        <el-table-column label="字典编码" prop="code" width="150" align="center" sortable :show-overflow-tooltip="true"/>
        <!--<SkyTag :tagOptions="skyDict['字典类型']" :value="scope.row.type"></SkyTag>-->
        <el-table-column label="字典分类" prop="type" width="150" align="center" sortable :show-overflow-tooltip="true"/>
        <el-table-column label="字典值类型" prop="valueType" width="150" align="center" sortable :show-overflow-tooltip="true"/>
        <el-table-column label="状态" prop="status" width="100" align="center" :show-overflow-tooltip="true">
          <template #default="scope">
            <el-switch
              v-model="scope.row.status"
              style="--el-switch-on-color: #409eff; --el-switch-off-color: #ff4949"
              active-text="启用"
              inactive-text="禁用"
              inline-prompt
            />
          </template>
        </el-table-column>
        <el-table-column label="排序" prop="sort" width="100" align="center" sortable :show-overflow-tooltip="true"/>
        <!--{{ useSkyDeptObj(skyDept.dept, scope.row.belong_dept) }}-->
        <el-table-column label="数据归属部门" prop="belongDept" width="170" align="center" sortable
                         :show-overflow-tooltip="true"/>
        <el-table-column label="备注" prop="remark" width="200" align="center" sortable :show-overflow-tooltip="true"/>
        <el-table-column label="创建人" prop="creator" width="150" align="center" sortable :show-overflow-tooltip="true"/>
        <el-table-column label="修改人" prop="modifier" width="150" align="center" sortable :show-overflow-tooltip="true"/>
        <el-table-column label="创建时间" prop="createTime" width="180" align="center" sortable
                         :show-overflow-tooltip="true"/>
        <el-table-column label="修改时间" prop="updateTime" width="180" align="center" sortable
                         :show-overflow-tooltip="true"/>
        <el-table-column label="操作" align="center" width="120" fixed="right">
          <template #default="{ row }">
            <el-tooltip content="修改🌻" placement="top">
              <el-button
                type="primary"
                icon="Edit"
                circle
                plain
                @click="method.handleUpdate(row)"
              ></el-button>
            </el-tooltip>
            <el-tooltip content="删除🌻" placement="top">
              <el-button
                type="danger"
                icon="Delete"
                circle
                plain
                @click="method.handleDelete(row)"
              ></el-button>
            </el-tooltip>
          </template>
        </el-table-column>
      </el-table>
      <br/>
      <!-- 分页 -->
      <el-pagination
        v-model:current-page="pageData.pageParams.page"
        v-model:page-size="pageData.pageParams.pageSize"
        v-show="pageData.total > 0"
        background
        :page-sizes="[10, 20, 50, 100, 200]"
        :layout="isScreen?'total, sizes, jumper':'total, sizes, prev, pager, next, jumper'"
        :total="pageData.total"
        @size-change="method.handleListPage"
        @current-change="method.handleListPage"
      />
      <!-- 添加 OR 修改 -->
      <SkyDrawer
        ref="skyDrawerRef"
        :title="pageData.title"
        @skyConfirm="method.handleConfirm"
        @skyCancel="method.handleCancel"
        :loading="pageData.confirmLoading"
      >
        <template #content>
          <el-form ref="formRef" :rules="pageData.rules" :model="pageData.form" label-width="auto" status-icon>
            <cf-input
              :sm="24"
              label="字典名称"
              prop="name"
              :model="pageData.form"
              :disabled="!!pageData.form.id"
            />
            <cf-input
              :sm="24"
              label="字典编号"
              prop="code"
              :model="pageData.form"
            />
            <cf-select
              :sm="24"
              label="字典分类"
              prop="type"
              :model="pageData.form"
              :disabled="!!pageData.form.id"
              :options="[
                {label: '普通字典', value: 1},
              ]"
              :option-label="'label'"
              :option-value="'value'"
            />
            <cf-select
              :sm="24"
              label="字典值类型"
              prop="valueType"
              :model="pageData.form"
              :disabled="!!pageData.form.id"
              :options="[
                {label: '字符串', value: 1},
              ]"
              :option-label="'label'"
              :option-value="'value'"
            />
            <cf-input-number
              :sm="24"
              label="排序"
              prop="sort"
              :model="pageData.form"
            />
            <cf-switch
              v-if="!!pageData.form.id"
              :sm="24"
              label="状态"
              prop="status"
              :model="pageData.form"
            />
            <cf-input
              :sm="24"
              label="备注"
              prop="remark"
              :type="'textarea'"
              :model="pageData.form"
              :rows="2"
            />
          </el-form>
          <el-text class="mx-1" type="primary">{{ pageData.form }}</el-text>
        </template>
      </SkyDrawer>
    </SkyCard>
  </div>
</template>

<style scoped lang="scss">

</style>
